<script setup>
import {ref, unref} from "vue";

const props = defineProps({
  text: {
    type: String,
    default: ""
  },
  autoplay: {
    type: Boolean,
    default: false,
  }
})

const emits = defineEmits(["animationend"])
const animationendCount = ref(0);
const key = ref(`k${Date.now()}`);
const isPlay = ref(props.autoplay);

function animationend() {
  animationendCount.value += 1;
  if (unref(animationendCount) === props.text.length) {
    emits("animationend", true)
  }
}

function play() {
  key.value = `k${Date.now()}`;
  isPlay.value = true;
}

defineExpose({
  play
})
</script>

<template>
  <div :key="key">
    <span v-for="(x, i) of text" :class="['item', {play: isPlay}]" :style="`--s: ${i * 200}ms`"
          @animationend="animationend">{{ x }}</span>
  </div>
</template>

<style scoped>
.item {
  opacity: 0;
}

.play {
  animation: 0.5s ease var(--s) 1 normal forwards running change-opacity;
}

@keyframes change-opacity {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
</style>
